#ifndef SIP_MANAGER_H
#define SIP_MANAGER_H

#include <string>
#include <atomic>
#include <functional>

// PJSIP
#include <pjsua-lib/pjsua.h>
#include <pjsip/sip_endpoint.h>

#include "Config.h"
#include "Logger.h"

class SipManager {
public:
    // 获取单例实例
    static SipManager& getInstance();
    
    // 初始化SIP库和账户
    bool initialize();
    
    // 注册SIP账户
    bool registerAccount();
    
    // 发送SIP消息
    bool sendMessage(const std::string& target_uri, const std::string& content, const std::string& content_type = "Application/MANSCDP+xml");
    
    // 处理收到的SIP消息
    bool handleMessage(pjsip_rx_data *rdata);
    
    // 处理传入的呼叫请求 - 由Application类调用
    bool handleIncomingCall(pjsua_acc_id acc_id, pjsua_call_id call_id, pjsip_rx_data *rdata);
    
    // 关闭并清理SIP资源
    void shutdown();
    
    // 获取账户ID
    pjsua_acc_id getAccountId() const;
    
    // 设置回调函数
    void setCallbacks(
        std::function<void(pjsua_acc_id)> on_reg_state_cb,
        std::function<void(pjsua_acc_id, pjsua_call_id, pjsip_rx_data*)> on_incoming_call_cb,
        std::function<void(pjsua_call_id, pjsip_event*)> on_call_state_cb,
        std::function<void(pjsua_call_id)> on_call_media_state_cb,
        std::function<pj_bool_t(pjsip_rx_data*)> on_rx_request_cb
    );
    
    // 是否已注册
    bool isRegistered() const;
    
private:
    // 私有构造函数（单例模式）
    SipManager();
    
    // 禁止拷贝和赋值
    SipManager(const SipManager&) = delete;
    SipManager& operator=(const SipManager&) = delete;
    
    // 析构函数
    ~SipManager();
    
    // 静态回调函数
    static void onRegState(pjsua_acc_id acc_id);
    static void onIncomingCall(pjsua_acc_id acc_id, pjsua_call_id call_id, pjsip_rx_data *rdata);
    static void onCallState(pjsua_call_id call_id, pjsip_event *e);
    static void onCallMediaState(pjsua_call_id call_id);
    static pj_bool_t onRxRequest(pjsip_rx_data *rdata);
    
    // 静态回调函数存储
    static std::function<void(pjsua_acc_id)> s_on_reg_state_cb;
    static std::function<void(pjsua_acc_id, pjsua_call_id, pjsip_rx_data*)> s_on_incoming_call_cb;
    static std::function<void(pjsua_call_id, pjsip_event*)> s_on_call_state_cb;
    static std::function<void(pjsua_call_id)> s_on_call_media_state_cb;
    static std::function<pj_bool_t(pjsip_rx_data*)> s_on_rx_request_cb;
    
    // 静态消息处理模块
    static pjsip_module s_message_module;
    
    // 账户ID
    pjsua_acc_id acc_id;
    
    // 是否已注册
    std::atomic<bool> registered;
};

#endif // SIP_MANAGER_H 